package com.changgou.filter;

import com.changgou.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 * 实现用户权限校验
 * 实现两个fun，拦截和排序
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    //定义指定令牌名
    private static final String AUTHORIZE_TOKEN = "Authorization";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//各微服务要进行权限校验，只能通过请求头的方式校验，所以我们要把请求封装到header中
        //获取用户令牌信息，优先顺序 头、参数、cookie
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
boolean  theTokenHeader= true; //flag一下，如果为false令牌token就没在头文件中

        if(StringUtils.isEmpty(token)){
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
            theTokenHeader=false;

            if(StringUtils.isEmpty(token)){
                HttpCookie httpCookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
                if(httpCookie !=null){
                    token = httpCookie.getValue();
                }
                else {//没有携带令牌就拦截
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }
        }


        //有令牌就校验
        try{
            JwtUtil.parseJWT(token);
        }catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //放行前要判断token令牌是否在头文件中
        //request.mutate().header(AUTHORIZE_TOKEN,token);

        return chain.filter(exchange);
    }

    /**
     * 越小就先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
